/**
 * Created by baijs on 2016/12/2.
 */


exports = module.exports = function (app, mongoose) {
    var userSchema = mongoose.Schema({
        username: {type: String, unique: true},
        password: String,
        email: {type: String, unique: true},
        roles: [
            {type: mongoose.Schema.Types.ObjectId, ref: 'Role'}
        ],
        active: String,
        createTime: {type: Date, default: Date.now},
        resetPasswordToken: String,
        resetPasswordExpires: Date
    });

    userSchema.methods.canPlayRoleOf = function (role) {
        if (role === "admin" && this.roles.admin) {
            return true;
        } else if (role === "account" && this.roles.account) {
            return true;
        }

        return false;
    };

    userSchema.methods.defaultReturnUrl = function () {
        var returnUrl = '/';
        if (this.canPlayRoleOf('account')) {
            returnUrl = '/account/';
        }

        if (this.canPlayRoleOf('admin')) {
            returnUrl = '/admin/';
        }

        return returnUrl;
    };
    userSchema.statics.encryptPassword = function (password, done) {
        var bcrypt = require('bcrypt');
        bcrypt.genSalt(10, function (err, salt) {
            if (err) {
                return done(err);
            }

            bcrypt.hash(password, salt, function (err, hash) {
                done(err, hash);
            });
        });
    };
    userSchema.statics.validatePassword = function (password, hash, done) {
        var bcrypt = require('bcrypt');
        bcrypt.compare(password, hash, function (err, res) {
            done(err, res);
        });
    };

    userSchema.index({ username: 1 }, { unique: true });
    userSchema.index({ email: 1 }, { unique: true });
    userSchema.index({ timeCreated: 1 });

    app.db.model('User', userSchema);
};